import json
import requests
from django import http
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render, redirect

from django.views import View
from apps.singers.models import Artist, Album, follow_artist
from apps.users.models import Album_Follow, PlayList_Follow

from utils.singer_album import album_detail, album_similar, album_song
from utils.singer_detail import singer_detail, singer_album, singer_mv


class SingersView(View):
    """歌手"""
    def get(self, request, page_num):
        # 获取前十歌手
        url = "http://musicapi.leanapp.cn/top/artists?offset=0&limit=10"
        content = requests.get(url)
        ret = json.loads(content.text)
        i = 0
        b = 0
        first_lists = []
        try:
            while b <= 9:
                singer_pic = ret['artists'][i]['picUrl']  # 歌手图片
                singer_name = ret['artists'][i]['name']  # 歌手名字
                singer_id = ret['artists'][i]['id']  # 歌单id

                i += 1
                b += 1
                dicts = {
                    'singer_id': singer_id,
                    'singer_name':singer_name,
                    'singer_pic': singer_pic,
                }
                first_lists.append(dicts)
        except Exception as e:
            print(e)
        username = request.session.get('username')
        #  获取所有的歌手
        singer_all = Artist.objects.all()
        page_num = int(page_num)
        try:
            paginator = Paginator(singer_all, 100)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages
        except EmptyPage:
            return http.HttpResponseNotFound('歌手不存在')

        follow_singer_lists = request.session.get("follow_list")
        user_id = request.session.get('user_id')
        aaa = ''
        try:
            singer_follow = follow_artist.objects.filter(user_id=user_id)
            aaa = singer_follow
        except Exception as e:
            pass
        content = {
            'singer_follow': aaa,
            'first_lists':first_lists,
            'singers': singer_all,
            'page_orders': page_orders,
            'total_page': total_page,
            'page_num': page_num,
            'follow_singer_list': follow_singer_lists,
            'username': username
        }

        return render(request, 'singer.html', content)


class Singers_detail_View(View):
    """歌手详情"""
    def get(self, request):
        artist_id = request.GET.get('id')
        # 获取了歌手的信息以及歌曲
        detail, lists = singer_detail(artist_id)
        # 获取此歌手的专辑
        album_list = singer_album(artist_id)
        # 歌手的mv
        mv_list = singer_mv(artist_id)

        user_id = request.session.get('user_id')

        singer_user = 0
        user_follow = follow_artist.objects.all()
        for x in user_follow:
            if x.artist_id == artist_id and x.user_id == user_id:
                singer_user = 1


        context={
            'detail': detail,
            'lists': lists,
            'album_list': album_list,
            'mv_list': mv_list,
            'id': artist_id,
            'user_follow': user_follow,
            'singer_user': singer_user,
            'user_id': user_id
        }

        return render(request, "detail.html", context)

    def post(self, request):
        # 获取数据
        json_dict = json.loads(request.body.decode())
        singer_img = json_dict.get('singer_img')
        singer_name = json_dict.get('singer_name')
        singer_id = json_dict.get("singer_id")
        user_id = json_dict.get("user_id")
        active_like = json_dict.get("active_like")
        print(singer_img, singer_name, singer_id, user_id, active_like)
        if user_id == None:
            return http.JsonResponse({'errmsg': '登录后即可关注', 'errno': 1})

        if not all([singer_img, singer_name, singer_id, active_like]):
            return http.JsonResponse({'errmsg': '参数错误', 'errno': 2})


        try:
            a = follow_artist.objects.create(user_id=user_id, artist_id=singer_id, artist_img=singer_img,
                                             artist_name=singer_name)
            a.save()
        except Exception as e:
            return http.JsonResponse({'errmsg': '关注失败', 'errno': 3})

        return http.JsonResponse({'errmsg': '关注成功', 'errno': 0})

    def delete(self, request):
        # 获取数据
        json_dict = json.loads(request.body.decode())
        singer_id = json_dict.get("song_id")
        user_id = json_dict.get("user_id")
        active_like = json_dict.get("del_like")

        if not all([singer_id, user_id, active_like]):
            return http.JsonResponse({'errmsg': '参数错误', 'errno': 2})

        list_user = follow_artist.objects.filter(user_id=user_id, artist_id=singer_id)
        if list_user:
            for x in list_user:
                follow_artist.objects.filter(id=x.id).delete()
            return http.JsonResponse({'errmsg': '取消关注成功', 'errno': 0})
        else:
            return http.JsonResponse({'errmsg': '取消关注失败', 'errno': 4})


class Album_View(View):
    """专辑"""
    def get(self, request, page_num):
        album_all = Album.objects.all()
        page_num = int(page_num)
        try:
            paginator = Paginator(album_all, 30)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages

        except EmptyPage:
            return http.HttpResponseNotFound('专辑不存在')

        context = {
                'album_lists': album_all,
                'page_orders': page_orders,
                'album_page': total_page,
                'page_num': page_num,
            }

        return render(request, "album.html", context)


class Album_ZH_View(View):
    """内地专辑"""
    def get(self, request, page_num):
        album_all = Album.objects.filter(album_type=1)
        page_num = int(page_num)
        # print(page_num, '=======================')
        try:
            paginator = Paginator(album_all, 30)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages

        except EmptyPage:
            return http.HttpResponseNotFound('专辑不存在')

        context = {
                'album_lists': album_all,
                'page_orders': page_orders,
                'album_page': total_page,
                'page_num': page_num,
            }

        return render(request, "album_zh.html", context)


class Album_KR_View(View):
    """韩国专辑"""
    def get(self, request, page_num):
        album_all = Album.objects.filter(album_type=2)
        page_num = int(page_num)
        # print(page_num, '=======================')
        try:
            paginator = Paginator(album_all, 30)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages

        except EmptyPage:
            return http.HttpResponseNotFound('专辑不存在')

        context = {
                'album_lists': album_all,
                'page_orders': page_orders,
                'album_page': total_page,
                'page_num': page_num,
            }

        return render(request, "album_kr.html", context)


class Album_EA_View(View):
        """欧美专辑"""

        def get(self, request, page_num):
            album_all = Album.objects.filter(album_type=3)
            page_num = int(page_num)
            # print(page_num, '=======================')
            try:
                paginator = Paginator(album_all, 30)
                page_orders = paginator.page(page_num)
                total_page = paginator.num_pages

            except EmptyPage:
                return http.HttpResponseNotFound('专辑不存在')

            context = {
                'album_lists': album_all,
                'page_orders': page_orders,
                'album_page': total_page,
                'page_num': page_num,
            }

            return render(request, "album_ea.html", context)


class Album_JP_View(View):
    """日本专辑"""
    def get(self, request, page_num):
        album_all = Album.objects.filter(album_type=4)
        page_num = int(page_num)
        # print(page_num, '=======================')
        try:
            paginator = Paginator(album_all, 30)
            page_orders = paginator.page(page_num)
            total_page = paginator.num_pages

        except EmptyPage:
            return http.HttpResponseNotFound('专辑不存在')

        context = {
                'album_lists': album_all,
                'page_orders': page_orders,
                'album_page': total_page,
                'page_num': page_num,
            }

        return render(request, "album_jp.html", context)


class Album_Detail_View(View):
    """专辑详情页"""
    def get(self, request):
        id = request.GET.get('id')
        # 获取了专辑的相关信息
        album_detail_lists = album_detail(id)
        id1 = album_detail_lists[0]['id1']
        album_id = album_detail_lists[0]['album_id']
        album_time = album_detail_lists[0]['album_time']
        # 获取此歌手的相关专辑
        sim_list = album_similar(id1)
        # 获取专辑的歌曲
        all_id,all_album_list,song_count = album_song(album_id)

        username_id = request.session.get('user_id')

        user_id = request.session.get('user_id')
        playlist_name = PlayList_Follow.objects.filter(users_id=user_id)

        if user_id:
            is_album = Album_Follow.objects.filter(users_id=int(username_id), album_id=str(album_id))
        else:
            is_album = ''
        content = {
            'album_detail_list': album_detail_lists,  # 专辑详情
            'all_id': all_id,
            'all_album_list': all_album_list,
            'sim_list': sim_list,  # 相似专辑
            'username_id': username_id,
            'album_id': album_id,
            'song_count': song_count,
            'album_time': album_time,
            'is_album': is_album,
            'playlist_name': playlist_name,
        }

        return render(request, 'album_detail.html', content)

    def post(self, request):
        # 获取数据， 关注专辑
        json_dict = json.loads(request.body.decode())
        active_like = json_dict.get('active_like')
        album_id = json_dict.get('album_id')
        album_name = json_dict.get('album_name')
        album_pic = json_dict.get('album_pic')
        singer_id = json_dict.get('singer_id')
        singer_name = json_dict.get('singer_name')
        user_id = json_dict.get('user_id')
        album_song_count = json_dict.get('album_song_count')

        issue_time = json_dict.get('issue_time')
        # if album_id:
        if not all([active_like, album_id, album_name, album_pic, singer_id, singer_name, issue_time, album_song_count]):
            return http.JsonResponse({'errmsg': '登录后即可收藏123123', 'errno': 10})
        if not user_id:
            return http.JsonResponse({'errmsg': '登录后即可收藏123123333', 'errno': 11})
        try:
            Album_Follow.objects.create(album_id=album_id,
                                album_name=album_name,
                                users_id=user_id,
                                album_pic=album_pic,
                                singer_id=singer_id,
                                singer_name=singer_name,
                                issue_time=issue_time,
                                album_song_count = album_song_count
                                )
            return http.JsonResponse({'errmsg': '收藏成功', 'errno': 0})
        except Exception as e:
            print(e)
            return http.JsonResponse({'errmsg': '收藏失败', 'errno': 9})

    def delete(self, request):
        # 删除收藏
        json_dict = json.loads(request.body.decode())
        del_like = json_dict.get('del_like')
        user_id = json_dict.get('user_id')
        album_id = json_dict.get('album_id')

        if not all([del_like, user_id, album_id]):
            return http.JsonResponse({'errmsg': '参数错误', 'errno': 10})
        else:
            try:
                Album_Follow.objects.filter(users_id=user_id, album_id=album_id).delete()
                return http.JsonResponse({'errmsg': '取消收藏成功', 'errno': 0})

            except Exception as e:
                print(e)
                return http.JsonResponse({'errmsg': '取消收藏失败', 'errno': 10})
